﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using SmartVault.Net;
using SmartVault.Net.Http;
using SmartVault.Proto;

namespace SmartVault.Rest
{
    /// <summary>
    /// PublicClientProtocol
    /// 
    /// Provides the operations that an occur for a client incapable of authentication.
    /// 
    /// Delegated Operations (those you perform as a user *may* be performed at 
    /// the client by passing the access token back to your client). 
    /// </summary>
    public class PublicClientProtocol
    {
        private PublicClientCfg ClientCfg { get; set; }
        private Uri RootUri { get { return this.ClientCfg.RootUri; } }
        private MediaType MediaType { get { return this.ClientCfg.MediaType; } }
        private Encoding Encoding { get { return this.ClientCfg.Encoding; } }
        private string ClientId { get { return this.ClientCfg.ClientId; } }

        private NetWebClient Client
        {
            get { return new NetWebClient(new WebRequestInfo(this.RootUri, null, null, this.MediaType, this.Encoding)); }
        }

        public PublicClientProtocol(PublicClientCfg cfg)
        {
            this.ClientCfg = cfg;

        }

        /// <summary>
        /// Return the endpoint we can direct a user to in order to get a URL you can direct the user to. This URL will prompt the
        /// user to authorize your application and provide a PIN the user can copy and paste into your application.
        /// </summary>
        /// <param name="useremail"></param>
        /// <returns></returns>
        public string GetPinRequestEndpoint(string useremail)
        {
            PINEndPointRequest.Builder bld = PINEndPointRequest.CreateBuilder();
            bld.ClientId = this.ClientId;

            ClientNetContext ctx = Client.Open(Constants.PinEndpointPath + Constants.Slash + useremail, HttpMethods.POST.ToString(), null);
            ctx.WritePayload(bld.Build());

            PINEndPointResponse rsp = ctx.ReadPayload<PINEndPointResponse>();

            return rsp.Message.AuthorizationUri;
        }

        /// <summary>
        /// GetDelegationAccessToken
        ///
        /// Create an access token that can be handed back to a client such as a web browser, mobile application, etc.
        /// </summary>
        /// <param name="userEmail"></param>
        /// <param name="userPin">User PIN provided by user</param>
        /// <returns></returns>
        public UserCfg GetDelegationAccessToken(string userEmail, string userPin)
        {
            DelegationTokenRequest.Builder cbld = DelegationTokenRequest.CreateBuilder();
            cbld.UserEmail = userEmail;

            DelegationTokenRequest.Types.PINInfo.Builder pbld = DelegationTokenRequest.Types.PINInfo.CreateBuilder();
            pbld.ClientId = this.ClientId;
            pbld.Pin = userPin;
            cbld.PinInfo = pbld.Build();

            ClientNetContext ctx = Client.Open(Constants.DelegationTokenPath, HttpMethods.POST.ToString(), null);
            ctx.WritePayload(cbld.Build());
            DelegationTokenResponse dtoken = ctx.ReadPayload<DelegationTokenResponse>();
            return new UserCfg(userEmail, dtoken, ClientCfg);
        }

        /// <summary>
        /// CreateDelegatedProtocol
        /// 
        /// Create an object that can be used to perform operations as the user. This method is useful if the client operations
        /// are occuring from your web server -- say rather than a web browser.
        /// </summary>
        /// <param name="userEmail">User to impersonate</param>
        /// <param name="userPin">User PIN provided by user</param>
        /// <returns></returns>
        public DelegatedProtocol CreateDelegatedProtocol(string userEmail, string userPin)
        {
            return new DelegatedProtocol(GetDelegationAccessToken(userEmail, userPin));
        }
    }
}
